import { Injectable } from '@angular/core'
import { NzMessageService } from 'ng-zorro-antd'

@Injectable({
  providedIn: 'root',
})

export class FileService {

  private counter = 0
  constructor(public msg: NzMessageService) {}
  getFileKey(inputFile) {
    const file = inputFile
    const ext = this.getFileExtension(file.name)
    const id = this.guid('a_')
    file.id = id
    const key = ext ? `${file.id}.${ext}` : file.id
    return key
  }

  getFileExtension(filename) {
    const tempArr = filename.split('.')
    let ext
    if (tempArr.length === 1 || (tempArr[0] === '' && tempArr.length === 2)) {
      ext = ''
    } else {
      ext = tempArr.pop().toLowerCase() // get the extension and make it lower-case
    }
    return ext
  }

  guid(prefix) {
    let guid = new Date().getTime().toString(32)
    for (let i = 0; i < 5; i++) {
      guid += Math.floor(Math.random() * 65535).toString(32)
    }
    return (prefix || 'o_') + guid + (this.counter++).toString(32)
  }

  validateFile(file, importType) {
    const re = /^(\d{8})_(Add(?:[a-zA-Z])*)_(\d{8})_(\d{3})\.xlsx?$/
    if (!re.test(file.name)) {
      this.msg.error('invalid file name')
      return false
    }
    const match = re.exec(file.name)
    const tp = match[2]
    const mapping = {
      AddMerchant: 'merchant',
      AddStore: 'store',
      AddTerminal: 'terminal',
    }
    if (mapping[tp] !== importType) {
      this.msg.error('operation does not match')
      return false
    }
    return true
  }
}
